package com.assistant.market.modules.market.app;

import com.assistant.market.modules.market.app.cmd.MarketIssueInsertCmd;
import com.assistant.market.modules.market.app.cmd.MarketIssueListCmd;
import com.assistant.market.modules.market.domain.MarketIssue;
import com.assistant.market.modules.market.domain.gateway.MarketIssueGateway;
import com.assistant.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MarketIssueService {

    @Autowired
    private MarketIssueGateway marketIssueGateway;

    public List<MarketIssue> list(MarketIssueListCmd cmd) {
        if (StringUtils.hasLength(cmd.getKeyword())) {
            final MarketIssue probe = new MarketIssue();
            probe.setTitle(cmd.getKeyword());
            probe.setRemarks(cmd.getKeyword());
            probe.setResolve(cmd.getKeyword());
            probe.setAuthor(cmd.getKeyword());
            probe.setComments(cmd.getKeyword());
            final ExampleMatcher exampleMatcher = ExampleMatcher.matchingAny()
                    .withMatcher("title", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("remarks", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("resolve", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("author", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("comments", ExampleMatcher.GenericPropertyMatchers.contains());
            return marketIssueGateway.findAll(Example.of(probe, exampleMatcher));
        }
        return marketIssueGateway.findAll();
    }

    public void insert(MarketIssueInsertCmd cmd) {
        MarketIssue marketIssue = new MarketIssue();
        BeanUtils.copyProperties(cmd, marketIssue);
        marketIssueGateway.save(marketIssue);
    }
}
